package com.gyhoo.firstbootdemo.controller;

import com.gyhoo.firstbootdemo.dao.DepartmentDao;
import com.gyhoo.firstbootdemo.dao.EmployeeDao;
import com.gyhoo.firstbootdemo.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.Map;

@Controller
public class EmployeeController {
    private EmployeeDao employeeDao;
    private DepartmentDao departmentDao;

    @Autowired
    public EmployeeController(EmployeeDao employeeDao, DepartmentDao departmentDao) {
        this.employeeDao = employeeDao;
        this.departmentDao = departmentDao;
    }



    @RequestMapping("/emps")
    public String toList(Map map){
        map.put("emps",employeeDao.getEmployees());
        return "/emp/list";
    }

    //跳转到添加员工页面，查询所有部门
    @GetMapping("/emp")
    public String toAddPage(Map map){
        //查出所有部门信息
        map.put("departments",departmentDao.getDepartments());
        return "emp/add";
    }

    //添加员工
    @PostMapping("/emp")
    public String addEmployee(Employee employee){
//        System.out.println("insert=>" + employee);
        employeeDao.insertEmployee(employee);
        //重定向到这个请求
        return "redirect:/emps";
    }

    //跳转到修改员工页面
    @GetMapping("/emp/{id}")
    public String toUpdatePage(@PathVariable("id")Integer id,Map map){
        //查询员工信息
        Employee employee = employeeDao.getEmployeeById(id);
        map.put("employee",employee);
        //查询所有部门信息
        Collection departments = departmentDao.getDepartments();
        map.put("depts",departments);
        return "emp/update";
    }

    //修改员工
    @PostMapping("/updateEmp")
    public String updateEmp(Employee employee){
        System.out.println("debug=>" + employee);
        employeeDao.insertEmployee(employee);
        return "redirect:/emps";
    }

    //删除员工
    @RequestMapping("deleteEmp/{id}")
    public String deleteEmp(@PathVariable("id")Integer id){
        employeeDao.deleteEmployee(id);
        return "redirect:/emps";
    }
}
